var goodsBatchCommit = new XFApp.client();
XFApp.client.prototype.goodsCommit = {
	
	urlItems:{
		getDict: basePath + "/nt/packageForstats/goodsRecord/getDiction",
		getSmallClass: basePath + "/nt/packageForstats/goodsRecord/loadGoodsClass",
		saveGoodsRUL: basePath + "/nt/packageForstats/goodsRecord/saveGoods",
		submitGoodsUrl: basePath +"/nt/packageForstats/goodsRecord/submitGoods"
	},
	/**
	 * 绑定页面事件
	 */
	event : function(){
		var _this = this;
		$("#copy_btn").on("click",function(){
			goodsBatchCommit.goodsCommit.viewData = goodsBatchCommit.goodsCommit.getGoodsViewData();
			$("#goods_batch_commit_modal_gname").html(_this.viewData.gname);
			$("#goods_batch_commit_modal").modal()
			if(!$("#goodsNum").val()) $("#goodsNum").attr('value',10);
			_this.giveSegmentValue();
		});
		
		$("#goods_batch_commit_product_grid").on("click",function(){
			_this.calculateWeightAndAmountSegment();
		});
		
		$("#weightEnd").on("blur",function(){
			_this.checkData();
		});
		$("#weightSrart").on("blur",function(){
			_this.checkData();
		});
		$("#amountEnd").on("blur",function(){
			_this.checkData();
		});
		$("#amountStart").on("blur",function(){
			_this.checkData();
		});
		
		$("#btnSubmitCopyGoods").on("click",function(){
			_this.submitCopyGoods();
		});
		$("#goods_batch_commit_reset").on("click",function(){
			$("#goods_batch_commit_form")[0].reset();
			var arr = new Array();
			$("#goods_batch_commit_grid").html($("#goods_batch_commit_tmpl").render(arr))
		});
	},
	/**
	 * 提交商品备案信息
	 */
	submitCopyGoods: function(){
		this.getDiction(this.getDictCodeByName);
	},
	/**
	 * 发送提交请求
	 */
	sendSubmitPost: function(obj){
		goodsBatchCommit.goodsCommit.successCount = 0;
		goodsBatchCommit.goodsCommit.errorCount = 0;
		goodsBatchCommit.goodsCommit.loadingDialog = webDialogUtil.loading('处理中...');
		$("[name='copyGoodsWeight']").each(function(){
			var gopyGoodsWeight = $(this).val();
			var copyGoodsAmount = $($(this).parent().next().children()).val();
			obj.prodweight = gopyGoodsWeight;
			obj.price = copyGoodsAmount;
			$.ajax({
				url:goodsBatchCommit.goodsCommit.urlItems.submitGoodsUrl,
				dataType:'json',
				type:'post',
				data: $.param(obj),
				success:function(data){
					
					if(data.isSuccess == true){
						goodsBatchCommit.goodsCommit.successCount += 1;
					}else{
						
					}
					if(goodsBatchCommit.goodsCommit.successCount == $("[name='copyGoodsWeight']").length){
						goodsBatchCommit.goodsCommit.loadingDialog.close();
						webDialogUtil.simpleAlert("成功提交"+$("[name='copyGoodsWeight']").length+"条备案", "温馨提示"); 
					}
				},
				error:function(){
					  webDialogUtil.simpleAlert("批量提交备案失败", "温馨提示"); 
				}
			});
		});
	},
	successCount: 0,
	errorCount: 0,
	loadingDialog: {},
	/**
	 * 取出提交需要用到的数据并提交
	 */
	cleanDataAndSubmit: function(){
		var obj = {};
		obj.id = '';
		obj.version = '';
		obj.detailId = '';
		obj.customercode = this.viewData.customscode;
		obj.itemname = this.viewData.itemname;
		obj.customscode = this.viewData.customscode;
		obj.gcode = this.viewData.gcode;
		obj.gname = this.viewData.gname;
		obj.unit = this.viewData.unit;
		obj.unit1 = this.viewData.unit1;
		obj.unit2 = this.viewData.unit2;
		//obj.prodweight = weight;
		//obj.price = amount;
		obj.currency = this.viewData.currency;
		obj.mainClassDictCode = this.viewData.mainClassDictCode;
		obj.gcodeFilter = '';
		obj.gnameFilter = '';
		obj.customername = this.viewData.customername;
		obj.ebpcode = this.viewData.ebpcode;
		obj.ebpname = this.viewData.ebpname;
		obj.ebccode = this.viewData.ebccode;
		obj.ebcname = this.viewData.ebcname;
		obj.agentcode = this.viewData.agentcode;
		obj.agentname = this.viewData.agentname;
		//获取商品小类
		$.ajax({
			url:this.urlItems.getSmallClass,
			dataType:'json',
			type:'post',
			data: {
				goodsDictCode: this.viewData.mainClassDictCode,
				goodsDictName: 	this.viewData.mainClassDictName
			},
			success:function(data){
				var _this = goodsBatchCommit.goodsCommit;
				var list = data.result;
				for(var i = 0;i <list.length;i ++){
					if(_this.viewData.classDictDataId == list[i].dictName){
						obj.classDictDataId = list[i].dictCode;
						continue;
					}
				}
				//提交数据
				_this.sendSubmitPost(obj);
			},
			error:function(){
				  webDialogUtil.simpleAlert("查询商品小类数据字典失败", "温馨提示"); 
			}
		});
	},
	/**
	 * 根据name提取code  （数据字典）
	 */
	getDictCodeByName: function(data){
		//单位
		var unitDict = data.units;
		//商品大类
		var classDict = data.classDictDataId;
		//商品小类
		//var 
		//申报海关
		var customscode = data.customerCodes;
		//币制
		var currencys = data.currencys;
		
		var _this = goodsBatchCommit.goodsCommit;
		for(var i = 0;i <unitDict.length;i ++){
			if(_this.viewData.unit == unitDict[i].dictName){
				_this.viewData.unit = unitDict[i].dictCode;
			}
			if(_this.viewData.unit1 == unitDict[i].dictName){
				_this.viewData.unit1 = unitDict[i].dictCode;
			}
			if(_this.viewData.unit2 == unitDict[i].dictName){
				_this.viewData.unit2 = unitDict[i].dictCode;
			}
		}
		for(var i = 0;i <classDict.length;i ++){
			if(_this.viewData.mainClassDictCode == classDict[i].dictName){
				_this.viewData.mainClassDictCode = classDict[i].dictCode;
				_this.viewData.mainClassDictName = classDict[i].dictName;
				continue;
			}
			
		}
		for(var i = 0;i <customscode.length;i ++){
			if(_this.viewData.customSelect == customscode[i].dictName){
				_this.viewData.customscode = customscode[i].dictCode;
				continue;
			}
		}
		for(var i = 0;i <currencys.length;i ++){
			if(_this.viewData.currency == currencys[i].dictName){
				_this.viewData.currency = currencys[i].dictCode;
			}
		}
		
		
		
		_this.cleanDataAndSubmit(1,2);
	},
	/**
	 * 获取备案信息时需要用到的数据
	 */
	getGoodsViewData: function(){
		var viewData = {};
		//通过遍历元素获取商品的属性名称和其对应的值
		if($("input").length>10){
			$("input[type='text']").each(function(){
				if($(this).hasClass("sug_select")){
					viewData[$(this).attr("name")] = $(this).attr("data-id");
				}else{
					viewData[$(this).attr("name")] = $(this).val();
				}
			});

			$("#base_info span[type='text']").each(function(){
				if(!!$(this).text()){
					viewData[$(this).attr("name")] = $(this).text();
				}
			});
		}else{
			$("span").each(function(){
				if($(this).attr('name')){
					viewData[$(this).attr('name')] = $(this).context.innerText;
				}
				if($(this).attr('id')){
					viewData[$(this).attr('id')] = $(this).context.innerText;
				}
			});
		}
		
		console.log(viewData);
		return viewData;
	},
	/**
	 * 根据已提交的商品备案的数据，自动填充待提交的商品的重量区间值，和价格区间值
	 */
	giveSegmentValue: function(){
		var count = $("#goodsNum").val();
		if(!count){
			webDialogUtil.simpleAlert("数量不能为空", "温馨提示");
		}
		var baseWeight = this.viewData.prodweight;
		var baseAmount = this.viewData.price;
	},
	/**
	 * 根据区间取值计算商品重量和价格分部
	 */
	calculateWeightAndAmountSegment: function(){
		var count = $("#goodsNum").val();
		if(!count){
			webDialogUtil.simpleAlert("数量不能为空", "温馨提示");
			return ;
		}
		var weightStart = parseFloat($("#weightSrart").val());
		if(!weightStart){
			webDialogUtil.simpleAlert("重量最小值不能为空", "温馨提示");
			return ;
		}
		var weightEnd = parseFloat($("#weightEnd").val());
		if(!weightEnd){
			webDialogUtil.simpleAlert("重量最大值不能为空", "温馨提示");
			return ;
		}
		var amountStart = parseFloat($("#amountStart").val());
		if(!amountStart){
			webDialogUtil.simpleAlert("价格最小值不能为空", "温馨提示");
			return ;
		}
		var amountEnd = parseFloat($("#amountEnd").val());
		if(!amountEnd){
			webDialogUtil.simpleAlert("价格最大值不能为空", "温馨提示");
			return ;
		}
		//计算区间值
		var weightSegment = (weightEnd-weightStart)/count;
		var amountSegment = (amountEnd-amountStart)/count;
		var arr = new Array();
		for(var i = 1;i <= count;i ++){
			var obj = {};
			obj.weight = this.changeTwoDecimal(weightStart + weightSegment);
			weightStart += weightSegment;
			obj.amount = this.changeTwoDecimal(amountStart + amountSegment);
			amountStart += amountSegment;
			obj.index = i;
			arr.push(obj);
		}
		$("#goods_batch_commit_grid").html($("#goods_batch_commit_tmpl").render(arr))
	},
	/**
	 * 保留两位小数
	 */
	changeTwoDecimal: function(x){
		var f_x = parseFloat(x);
		if (isNaN(f_x))
		{
		//alert('function:changeTwoDecimal->parameter error');
		return false;
		}
		f_x = Math.round(f_x *100)/100;
		return f_x;
	},
	/**
	 * 计算重量和价格的取值区间
	 */
	calculateWeightAndAmountRegion: function(obj){
		
		return "";
	},
	/**
	 * 校验输入数据是否合法
	 */
	checkData: function(){
		//最大商品重量、价格大于最小商品重量价格
		var weightStart = parseFloat($("#weightSrart").val());
		var weightEnd = parseFloat($("#weightEnd").val());
		var amountStart = parseFloat($("#amountStart").val());
		var amountEnd = parseFloat($("#amountEnd").val());
		if(weightStart && weightEnd<=weightStart){
			webDialogUtil.callbackConfrimAlert("商品最大重量必须大于商品最小重量", function (){
				document.getElementById('weightEnd').value = '';
				$("#weightEnd").focus().select();
			}, "温馨提示");
			return;
		}
		if(amountStart && amountEnd<=amountStart){
			webDialogUtil.callbackConfrimAlert("商品最大价格必须大于商品最小价格", function (){
				document.getElementById('amountEnd').value = '';
				$("#amountEnd").focus().select();
			},"温馨提示");
			return;
		}
		if(weightEnd && weightEnd<=weightStart){
			webDialogUtil.callbackConfrimAlert("商品最大重量必须大于商品最小重量", function (){
				document.getElementById('weightSrart').value = '';
				$("#weightSrart").focus().select();
			}, "温馨提示");
			return;
		}
		if(amountEnd && amountEnd<=amountStart){
			webDialogUtil.callbackConfrimAlert("商品最大价格必须大于商品最小价格", function (){
				document.getElementById('amountStart').value = '';
				$("#amountStart").focus().select();
			},"温馨提示");
			return;
		}
		
	},
	/**
	 * 校验输入框中的数值是否正确,
	 * param  digt 小数点后的位数
	 */
	chekFloatByDigt: function(obj,digt){
		 //检查是否是非数字值  
		//console.log(digt);
	     if (isNaN(obj.value)) {  
	         obj.value = "";  
	     }  
	     if (obj.value && digt) {  
	         //检查小数点后是否对于两位http://blog.csdn.net/shanzhizi  
	         if (obj.value.toString().split(".").length > 1 && obj.value.toString().split(".")[1].length > digt) {  
	             obj.value = obj.value.substring(0,obj.value.length-1);  
	         }  
	     }  
	},
	/**
	 * 获取数据字典信息
	 */
	getDiction: function(callback){
		var _this = this;
		$.ajax({
			url:_this.urlItems.getDict,
			dataType:'json',
			type:'post',
			success:function(data){
				//console.log(data);
				if(callback){
					callback(data);
				}
			},
			error:function(){
				  webDialogUtil.simpleAlert("查询数据字典失败", "温馨提示"); 
			}
		});
	},
	viewData: {}
	
	
}

$(function(){
	goodsBatchCommit.goodsCommit.event();
	//goodsBatchCommit.goodsCommit.viewData = goodsBatchCommit.goodsCommit.getGoodsViewData();
});